<!-- <template>
    <div class="course-credit-certification-page-container">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span>课程学分认证申请</span>
                </div>
            </template>
            <el-form :model="certificationForm" :rules="rules" ref="certificationFormRef" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="课程名称" prop="courseName">
                            <el-input v-model="certificationForm.courseName" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="证明图片" prop="imageUrl">
                            <el-upload
                                class="avatar-uploader"
                                :action="uploadImageUrl"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload"
                            >
                                <img v-if="certificationForm.imageUrl" :src="certificationForm.imageUrl" class="avatar">
                                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                            </el-upload>
                            <div class="el-upload__tip">
                                支持 JPG/PNG 格式，大小不超过 2MB。
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="认证描述" prop="description">
                            <el-input
                                type="textarea"
                                v-model="certificationForm.description"
                                :rows="4"
                                placeholder="请填写详细的认证描述（可选）"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20" class="form-buttons">
                    <el-col :span="24">
                        <el-form-item>
                            <el-button type="primary" @click="submitApplication" :loading="isSubmitting">提交申请</el-button>
                            <el-button @click="resetForm">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
    </div>
</template>

<script>
// 1. 【修改】直接引入整个 creditService 和 userManager
import creditService from '../services/creditService';
import { userManager } from '@/utils/user';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

// 定义后端使用的前缀，确保前后端一致性
const COURSE_CERT_PREFIX = "COURSE_CERT:"; 
export default {
  name: 'CourseCreditCertification',
  components: {
    Plus,
  },
  data() {
    return {
      isSubmitting: false,
      certificationForm: {
        applicantId: '',
        courseId: '',      // 新增：用于存储课程ID
        courseCredit: 0,   // 新增：用于存储课程学分
        courseName: '',
        imageUrl: '',
        description: '',
      },
      rules: {
        courseName: [
          { required: true, message: '课程名称不能为空', trigger: 'blur' },
        ],
      },
      uploadImageUrl: userManager.getServerUrl() + '/images/upload',
    };
  },

  created() {

    this.certificationForm.applicantId = userManager.getUserId();
    if (!this.certificationForm.applicantId) {
      ElMessage.error('无法获取用户信息，请重新登录！');
    }
  },
  mounted() {
    // 从路由查询参数中获取课程名称、ID和学分
    if (this.$route.query.courseName) {
      this.certificationForm.courseName = this.$route.query.courseName;
    } else {
      ElMessage.error('未找到课程名称，请从课程详情页进入！');
    }
    
    if (this.$route.query.courseId) {
      this.certificationForm.courseId = this.$route.query.courseId;
    } else {
      ElMessage.error('未找到课程ID，无法进行学分认证。');
      // 如果 courseId 缺失且后端严格要求，可能需要禁用提交或跳转
    }

    if (this.$route.query.courseCredit) {
      // 确保将学分解析为数字
      this.certificationForm.courseCredit = parseInt(this.$route.query.courseCredit, 10);
      if (isNaN(this.certificationForm.courseCredit)) {
        this.certificationForm.courseCredit = 0; // 如果解析失败，设为默认值
        ElMessage.warning('课程学分格式不正确，已设为0。');
      }
    } else {
      this.certificationForm.courseCredit = 0; // 如果未找到，设为默认值
      ElMessage.warning('未找到课程学分，已设为0。');
    }
  },
  methods: {
    handleAvatarSuccess(response, uploadFile) {
      if (response.code === 1000 && response.data) {
        this.certificationForm.imageUrl = response.data;
        ElMessage.success('图片上传成功！');
      } else {
        ElMessage.error(response.msg || '图片上传失败，请重试。');
      }
    },
    beforeAvatarUpload(file) {
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGorPNG) {
        ElMessage.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!');
      }
      return isJPGorPNG && isLt2M;
    },

    async submitApplication() {
      this.$refs.certificationFormRef.validate(async (valid) => {
        if (valid) {
          this.isSubmitting = true;

          // 核心修改：构建符合后端期望的 description 格式
          // 格式: COURSE_CERT:[courseId]:[courseCredit]:[courseName]:[originalDescription]
          let originalDescription = this.certificationForm.description || ''; // 获取用户输入的描述
          let finalDescription = `${COURSE_CERT_PREFIX}${this.certificationForm.courseId}:${this.certificationForm.courseCredit}:${this.certificationForm.courseName}`;
          
          if (originalDescription) {
              finalDescription += `:${originalDescription}`; // 如果用户有额外描述，则追加
          }

          const submissionData = {
            applicantId: this.certificationForm.applicantId,
            description: finalDescription, // 使用新的编码描述
            imageUrl: this.certificationForm.imageUrl,
          };

          try {
            const response = await creditService.createCertification(submissionData);

            if (response.code === 1000) {
              ElMessage.success(response.msg || '课程学分认证申请提交成功！');
              this.resetForm();
            } else {
              ElMessage.error(response.msg || '提交失败，请重试。');
            }
          } catch (error) {
            console.error('提交课程学分认证失败:', error);
            ElMessage.error('提交课程学分认证失败，请检查网络或稍后再试。');
          } finally {
            this.isSubmitting = false;
          }
        } else {
          ElMessage.warning('请检查表单填写是否完整。');
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.certificationFormRef.resetFields();
      this.certificationForm.imageUrl = '';
      this.certificationForm.description = '';
    },
  },
};
</script>
<style scoped>
.course-credit-certification-page-container {
    padding: 30px;
    background-color: #f0f2f5;
    min-height: calc(100vh - 80px);
    display: flex;
    justify-content: center;
    align-items: flex-start;
}

.box-card {
    width: 100%;
    max-width: 700px;
    margin-top: 30px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    border-radius: 8px;
}

.card-header {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 20px;
    font-weight: bold;
    color: #303133;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 20px;
}


.el-form-item {
    margin-bottom: 22px;
}

/* ElUpload 样式 */
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 120px;
    height: 120px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    text-align: center;
}
.avatar {
    width: 100%;
    height: 100%;
    display: block;
    object-fit: contain;
}


.el-upload__tip {
    margin-top: 5px;
    font-size: 12px;
    color: #999;
}

.form-buttons {
    padding-top: 15px;
    border-top: 1px solid #ebeef5;
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    gap: 15px;
}

/* 提交按钮的样式（可选，如果需要更特别的风格） */
.el-button--primary {
    /* 例如： background-color: #67C23A; */
    /* 例如： border-color: #67C23A; */
}
</style> -->
<template>
    <div class="course-credit-certification-page-container">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span>课程学分认证申请</span>
                </div>
            </template>
            <el-form :model="certificationForm" :rules="rules" ref="certificationFormRef" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="课程名称" prop="courseName">
                            <el-input v-model="certificationForm.courseName" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="证明图片" prop="imageUrl">
                            <el-upload
                                class="avatar-uploader"
                                :action="uploadImageUrl"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload"
                                @change="handleFileChange"  >
                                <img v-if="imagePreviewUrl" :src="imagePreviewUrl" class="avatar">
                                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                            </el-upload>
                            <div class="el-upload__tip">
                                支持 JPG/PNG 格式，大小不超过 2MB。
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="认证描述" prop="description">
                            <el-input
                                type="textarea"
                                v-model="certificationForm.description"
                                :rows="4"
                                placeholder="请填写详细的认证描述（可选）"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20" class="form-buttons">
                    <el-col :span="24">
                        <el-form-item>
                            <el-button type="primary" @click="submitApplication" :loading="isSubmitting">提交申请</el-button>
                            <el-button @click="resetForm">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import creditService from '../services/creditService';
import { userManager } from '@/utils/user';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const COURSE_CERT_PREFIX = "COURSE_CERT:"; 

export default {
  name: 'CourseCreditCertification',
  components: {
    Plus,
  },
  data() {
    return {
      isSubmitting: false,
      certificationForm: {
        applicantId: '',
        courseId: '',      
        courseCredit: 0,   
        courseName: '',
        imageUrl: '', // 用于存储最终的云端图片URL
        description: '',
      },
      rules: {
        courseName: [
          { required: true, message: '课程名称不能为空', trigger: 'blur' },
        ],
      },
      uploadImageUrl: userManager.getServerUrl() + '/images/upload',
      imagePreviewUrl: null, // 【新增】用于图片即时预览的URL
    };
  },

  created() {
    this.certificationForm.applicantId = userManager.getUserId();
    if (!this.certificationForm.applicantId) {
      ElMessage.error('无法获取用户信息，请重新登录！');
    }
  },
  mounted() {
    if (this.$route.query.courseName) {
      this.certificationForm.courseName = this.$route.query.courseName;
    } else {
      ElMessage.error('未找到课程名称，请从课程详情页进入！');
    }
    
    if (this.$route.query.courseId) {
      this.certificationForm.courseId = this.$route.query.courseId;
    } else {
      ElMessage.error('未找到课程ID，无法进行学分认证。');
    }

    if (this.$route.query.courseCredit) {
      this.certificationForm.courseCredit = parseInt(this.$route.query.courseCredit, 10);
      if (isNaN(this.certificationForm.courseCredit)) {
        this.certificationForm.courseCredit = 0; 
        ElMessage.warning('课程学分格式不正确，已设为0。');
      }
    } else {
      this.certificationForm.courseCredit = 0; 
      ElMessage.warning('未找到课程学分，已设为0。');
    }
  },
  methods: {
    // 【新增方法】处理文件选择事件，用于本地即时预览
    handleFileChange(file) {
      if (file.raw) {
        this.imagePreviewUrl = URL.createObjectURL(file.raw); // 创建本地预览URL
      } else {
        this.imagePreviewUrl = null;
      }
    },
    handleAvatarSuccess(response, uploadFile) {
      if (response.code === 1000 && response.data) {
        // 假设 response.data 已经是完整的 OSS URL，直接使用
        this.certificationForm.imageUrl = response.data; // 更新为云端URL，用于提交
        ElMessage.success('图片上传成功！');
      } else {
        ElMessage.error(response.msg || '图片上传失败，请重试。');
        this.certificationForm.imageUrl = ''; // 上传失败时清空云端URL
        this.imagePreviewUrl = null;         // 上传失败时清空本地预览
      }
    },
    beforeAvatarUpload(file) {
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGorPNG) {
        ElMessage.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!');
      }
      return isJPGorPNG && isLt2M;
    },

    async submitApplication() {
      this.$refs.certificationFormRef.validate(async (valid) => {
        if (valid) {
          this.isSubmitting = true;

          let originalDescription = this.certificationForm.description || ''; 
          let finalDescription = `${COURSE_CERT_PREFIX}${this.certificationForm.courseId}:${this.certificationForm.courseCredit}:${this.certificationForm.courseName}`;
          
          if (originalDescription) {
              finalDescription += `:${originalDescription}`; 
          }

          const submissionData = {
            applicantId: this.certificationForm.applicantId,
            description: finalDescription, 
            imageUrl: this.certificationForm.imageUrl, // 确保提交的是最终的云端URL
          };

          try {
            const response = await creditService.createCertification(submissionData);

            if (response.code === 1000) {
              ElMessage.success(response.msg || '课程学分认证申请提交成功！');
              this.resetForm();
            } else {
              ElMessage.error(response.msg || '提交失败，请重试。');
            }
          } catch (error) {
            console.error('提交课程学分认证失败:', error);
            ElMessage.error('提交课程学分认证失败，请检查网络或稍后再试。');
          } finally {
            this.isSubmitting = false;
          }
        } else {
          ElMessage.warning('请检查表单填写是否完整。');
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.certificationFormRef.resetFields();
      this.certificationForm.imageUrl = ''; // 清空云端URL
      this.certificationForm.description = '';
      // 注意：课程名称、ID和学分在 mounted 钩子中从路由填充，这里不重置
      // 如果需要重置为初始状态（如空字符串或0），请根据业务逻辑自行添加：
      // this.certificationForm.courseName = '';
      // this.certificationForm.courseId = '';
      // this.certificationForm.courseCredit = 0;
      this.imagePreviewUrl = null; // 【修改】重置即时预览URL
    },
  },
};
</script>
<style scoped>
.course-credit-certification-page-container {
    padding: 30px;
    background-color: #f0f2f5;
    min-height: calc(100vh - 80px);
    display: flex;
    justify-content: center;
    align-items: flex-start;
}

.box-card {
    width: 100%;
    max-width: 700px;
    margin-top: 30px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    border-radius: 8px;
}

.card-header {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 20px;
    font-weight: bold;
    color: #303133;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 20px;
}


.el-form-item {
    margin-bottom: 22px;
}

/* ElUpload 样式 */
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 120px;
    height: 120px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    text-align: center;
}
.avatar {
    width: 100%;
    height: 100%;
    display: block;
    object-fit: contain;
}


.el-upload__tip {
    margin-top: 5px;
    font-size: 12px;
    color: #999;
}

.form-buttons {
    padding-top: 15px;
    border-top: 1px solid #ebeef5;
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    gap: 15px;
}

/* 提交按钮的样式（可选，如果需要更特别的风格） */
.el-button--primary {
    /* 例如： background-color: #67C23A; */
    /* 例如： border-color: #67C23A; */
}
</style>